import { _decorator, assetManager, AudioClip, Component } from 'cc';
import { BYTEDANCE, WECHAT } from 'cc/env';
import { Game } from './core/Game';
import { Databus  } from './core/Databus';
import { UserLogin } from './platform/UserLogin';
import { PlatformSetting } from './platform/PlatformSetting';
import { queryRobotUserList, queryUserRankingList } from './services/UserInfo';

import { SendWebSocket } from './websocket/SendWebSocket';
import DataEventReport from './platform/DataEventReport';
import { ResourceManager } from './framework/ResourceManager';
import { uniConfig } from './config/UniConfig';
import { NetSoundManager } from './framework/SoundManager';
import { UniformFunction } from './platform/UniformFunction';
import { InterstitialAd } from './platform/ad/InterstitialAd';
import { MatrixCustomLeftAd } from './platform/ad/MatrixCustomLeftAd';
import { MatrixCustomRightAd } from './platform/ad/MatrixCustomRightAd';
import { MatrixCustomMultiAd } from './platform/ad/MatrixCustomMultiAd';
import { WxSdkManager } from './platform/ad/WxSdkManager';
const { ccclass, property } = _decorator;
const databus = Databus.Instance();
@ccclass('GameLaunch')
export class GameLaunch extends Component {
  public static instance: GameLaunch = null as unknown as GameLaunch;
  onLoad(): void {
    if (GameLaunch.instance) {
      return;
    }
    GameLaunch.instance = this;
    assetManager.loadRemote(`${uniConfig.backgroundMusicUrl}`, (err, audioClip) => {
      NetSoundManager.Instance().setBgClip(audioClip as AudioClip);
      console.log('load bg music ', err);
    });
    // 登陆Login
    new UserLogin().uniLogin();
    // 平台相关常用的设置
    new PlatformSetting().uniSetting();
    // 预拉取机器人信息
    queryRobotUserList(databus.selfInfo.userId, databus.selfInfo.playLevel.playLevel);
    queryUserRankingList(databus.selfInfo.userId, databus.selfInfo.playLevel.playLevel);
    // 入口有没有roomId
    databus.launchData.setRoomId(this.getLaunchRoomId());
    databus.launchData.setGameType(this.getLaunchGameType());
    console.log('launch app info xxxxx ', databus.launchData);

    this.onShow();


    WxSdkManager.initCustomCol33Ad();



    InterstitialAd.Instance().create();
    DataEventReport.Instance().reportSceneTime(7, 0, 'launch');

    ResourceManager.Instance().loadImageSpriteFrame(ResourceManager.DefaultUserHeaderImage, uniConfig.defaultXAvatarUrl);
  }
  start() {
    
    MatrixCustomLeftAd.Instance().create();
    MatrixCustomRightAd.Instance().create();
    MatrixCustomMultiAd.Instance().create();
  }
  update(deltaTime: number) {
    
  }

  public onShow() {
    const that = this;
    // 页面显示或从后台跳回小游戏时显示此页面时触发
    if (WECHAT) {
      wx.onShow(function (res: any) {
        console.log('app onshow ', res);
        const roomId = that.getQueryRoomId(res);
        if (roomId !== '') {
          const gameType = that.getQueryGameType(res);
          // 新加入游戏的，则加入好友对战
          if (!Game.Instance().status.isStarted()) {
            databus.launchData.setRoomId(roomId);
            databus.launchData.setGameType(gameType);
            that.joinRoom();
            databus.sceneStack.toMatchPage();
          } else { // 继续完成游戏

          }
        }
      });
    } else if (BYTEDANCE) {
      tt.onShow((res) => {
        console.log("启动参数：", res.query);
        console.log("来源信息：", res.refererInfo);
        console.log("场景值：", res.scene);
        console.log("启动场景字段：", res.launch_from, ", ", res.location);
        if (res.launch_from === "homepage" && res.location === "sidebar_card" && res.scene === "021036") {
          databus.showScene.isFromSideBar = true;
          // 跳转成功回调逻辑
          databus.outlook.updateQiuGanName('PerfectQiuGan');
          new UniformFunction().showInfoToast("获得精美球杆", 2000);
        } else {
          databus.showScene.isFromSideBar = false;
        }

        console.log('app onshow ', res);
        const roomId = that.getQueryRoomId(res);
        if (roomId !== '') {
          const gameType = that.getQueryGameType(res);
          // 新加入游戏的，则加入好友对战
          if (!Game.Instance().status.isStarted()) {
            databus.launchData.setRoomId(roomId);
            databus.launchData.setGameType(gameType);
            that.joinRoom();
            databus.sceneStack.toMatchPage();
          } else { // 继续完成游戏

          }
        }
      });
      tt.checkScene({
        scene: "sidebar",
        success: (res) => {
          console.log("check scene success: ", res.isExist);
          //成功回调逻辑
          databus.showScene.showRewardBonus = true;
        },
        fail: (res) => {
          console.log("check scene fail:", res);
          //失败回调逻辑
          databus.showScene.showRewardBonus = false;
        }
      });
    }
  }
  private getLaunchRoomId() {
    if (WECHAT) {
      const res = wx.getLaunchOptionsSync();
      return this.getQueryRoomId(res);
    } else if (BYTEDANCE) {
      const res = tt.getLaunchOptionsSync();
      return this.getQueryRoomId(res);
    }
    return '';
  }
  private getLaunchGameType() {
    if (WECHAT) {
      const res = wx.getLaunchOptionsSync();
      return this.getQueryGameType(res);
    } else if (BYTEDANCE) {
      const res = tt.getLaunchOptionsSync();
      return this.getQueryGameType(res);
    }
    return 0;
  }

  private getQueryRoomId(res: any) {
    if (res.hasOwnProperty('query') && res.query.hasOwnProperty('roomId')) {
      return res.query.roomId as string;
    }
    return '';
  }

  private getQueryGameType(res: any) {
    if (res.hasOwnProperty('query') && res.query.hasOwnProperty('gameType')) {
      return Number(res.query.gameType) as number;
    }
    return 0;
  }
  private joinRoom() {
    Game.Instance().battleCate.frientBattle();
    Game.Instance().setRoomId(databus.launchData.roomId);
    Game.Instance().gameType.setValueType(databus.launchData.gameType);
    Game.Instance().playUsers[0].started();
    Game.Instance().playUsers[1].human();
    new SendWebSocket().userStatus(Game.Instance().playUsers[0]);
  }
}

